package com.example.statistics.ui.purchase

import android.os.Bundle
import com.example.statistics.R
import com.example.statistics.bean.FinancingFeeBean
import com.example.statistics.bean.FuturesFeeBean
import com.example.statistics.bean.TaxFeeBean
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.ex.afterTextChangedListener
import kotlinx.android.synthetic.main.activity_financing_fee_edit.*
import java.io.Serializable
import java.math.BigDecimal
import java.util.*


/**
 * 融资费用
 *
 * 新协航； 1-180天：6%;
 *         利息 =（尾款+尾款手续费）* 天数 * 0.075 / 360
 *         180天以上：12%
 * 泽  厚；1-90天：7%*1.03
 *         利息 = （定金差额 + 尾款）* 天数 * 0.0721 / 360
 * 国  晟；1-90天：0.084
 *         利息 = （定金差额 + 尾款）* 天数 * 0.084 / 360
 * 翰  强；中进 0.076，其他0.08；90天以上：都18%
 *         利息=（定金差额+定金手续费+尾款+尾款手续费）* 天数 * 0.076 / 360
 * 同  华：1-90（0.06）90天以上：0.072
 *
 */
class FinancingFeeEditActivity : BaseActivity() {

    private var financingRate = 0.0
    private var feeMay = mutableMapOf<String, FuturesFeeBean>()
    private var financingBean = FinancingFeeBean()
    private val dayMillisecond = 24 * 60 * 60 * 1000


    override val title: String
        get() = intent.getStringExtra(Constants.TYPE) ?: "融资"

    private val interestCalculate: Double
        get() {
            return financingBean.financingDays
                    .mulEx(financingBean.financingAmount, 6)
                    .mulEx(financingBean.financingRate, 6)
                    .divEx(360, 2).toDouble()
        }

    private val startTimes: Long
        get() = tv_start_date.contentText?.parse()?.time ?: Date().time

    private val endTimes: Long
        get() = tv_end_date.contentText?.parse()?.time ?: Date().time

    private val financingDays: Long
        get() = (endTimes - startTimes) / dayMillisecond + 1


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_financing_fee_edit)
        val data = intent.getSerializableExtra(Constants.DATA)

        tv_start_date.onDateClicked {
            financingBean.startDate = it
            tv_days.contentText = financingDays.toString()
        }
        tv_end_date.onDateClicked {
            financingBean.endDate = it
            tv_days.contentText = financingDays.toString()
        }
        tv_days.afterTextChangedListener { editable, _ ->
            financingBean.financingDays = editable.toString().toIntOrNull()
            financingBean.financingInterest = interestCalculate
            tv_interest.contentText = financingBean.financingInterest.toString()
        }
        tv_amount.afterTextChangedListener { editable, _ ->
            financingBean.financingAmount = editable.toString().toDoubleOrNull()
            financingBean.financingInterest = interestCalculate
            tv_interest.contentText = financingBean.financingInterest.toString()
        }
        tv_rate.afterTextChangedListener { editable, _ ->
            financingBean.financingRate = editable.toString().toDoubleOrNull()
            financingBean.financingInterest = interestCalculate
            tv_interest.contentText = financingBean.financingInterest.toString()
        }
        initData(data)
        refresh()

        topBarRightText("保存") {
            val url = if (data is FinancingFeeBean) UrlConfig.PURCHASE_FINANCING_FEE_UPDATE else UrlConfig.PURCHASE_FINANCING_FEE_ADD
            httpPost<FinancingFeeBean>(url, config = {
                isShowDialog = true
                isSuccessToast = true
                listParams = listOf(
                        "ID" to financingBean.ID,
                        "containerNo" to financingBean.containerNo,
                        "purchaseProductId" to financingBean.purchaseProductId,
                        "financingType" to financingBean.financingType,
                        "financingAmount" to financingBean.financingAmount,
                        "financingRate" to financingBean.financingRate,
                        "financingInterest" to financingBean.financingInterest,
                        "startDate" to financingBean.startDate,
                        "endDate" to financingBean.endDate,
                        "financingDays" to financingBean.financingDays,
                )
            }) {
                activityFinish()
            }
        }
    }

    private fun initData(data: Serializable?) {
        val agentId = intent.getIntExtra(Constants.AGENT_ID, 0)
        val purchaseId = intent.getIntExtra(Constants.PURCHASE_PRODUCT_ID, 0)
        val containerNo = intent.getStringExtra(Constants.CONTAINER_NO).orEmpty()
        val endDate = intent.getStringExtra(Constants.DATE)

        when (agentId) {
            1 -> financingRate = 0.06 //新协航
            2 -> financingRate = 0.07.mulEx(1.03, 6).toDouble()//泽厚
            3 -> financingRate = 0.084//国晟
            4 -> financingRate = 0.076//翰强
            26 -> financingRate = 0.06//同化
        }
        financingBean.financingType = title
        financingBean.purchaseProductId = purchaseId
        financingBean.containerNo = containerNo
        financingBean.financingRate = financingRate
        financingBean.endDate = endDate
        if (data is List<*>) {
            tv_rate.contentText = financingRate.toString()
            val depositDifference: BigDecimal
            var balanceDifference: BigDecimal
            data.forEach {
                it as FuturesFeeBean
                feeMay[it.feeType] = it
            }
            when (agentId) {
                1 -> {//带手续费但是和保证金没关系
                    balanceDifference = feeMay["预付尾款"]?.totalFee
                            .subEx(feeMay["实际尾款"]?.totalFee).abs()
                }
                4 -> { //带手续费
                    depositDifference = feeMay["预付定金"]?.totalFee
                            .subEx(feeMay["实际定金"]?.totalFee)//定金差额
                    balanceDifference = feeMay["预付尾款"]?.totalFee
                            .addEx(feeMay["预付保证金"]?.totalFee)
                            .subEx(feeMay["实际尾款"]?.totalFee)
                            .subEx(feeMay["实际保证金"]?.totalFee).abs()//尾款差额

                    balanceDifference = balanceDifference.subEx(depositDifference).abs()
                }
                else -> { //不带手续费
                    depositDifference = feeMay["预付定金"]
                            ?.rmb.subEx(feeMay["实际定金"]?.rmb)//定金差额
                    balanceDifference = feeMay["预付尾款"]
                            ?.rmb.addEx(feeMay["预付保证金"]?.rmb)
                            .subEx(feeMay["实际尾款"]?.rmb)
                            .subEx(feeMay["实际保证金"]?.rmb).abs()//尾款差额

                    balanceDifference = balanceDifference.subEx(depositDifference)
                }
            }
            //尾款
            feeMay["实际尾款"]?.date?.goTimeFormat()?.let {
                tv_start_date.contentText = it
                financingBean.startDate = it
                financingBean.financingAmount = balanceDifference.toDouble()
                financingBean.financingDays = financingDays.toInt()
                financingBean.financingInterest = interestCalculate
            }


        } else if (data is TaxFeeBean) { //税款
            val taxAccount = data.totalFee
            if (taxAccount != 0.0) {
                tv_start_date.contentText = data.date
                financingBean.startDate = data.date.goTimeFormat().orEmpty()
                financingBean.financingAmount = taxAccount
                financingBean.financingDays = financingDays.toInt()
                financingBean.financingInterest = interestCalculate
            }
        } else if (data is FinancingFeeBean) {
            financingBean = data
        }
    }

    private fun refresh() {
        tv_start_date.contentText = financingBean.startDate
        tv_end_date.contentText = financingBean.endDate
        tv_amount.contentText = financingBean.financingAmount.toString()
        tv_rate.contentText = financingBean.financingRate.toString()
        tv_days.contentText = financingBean.financingDays.toString()
        tv_interest.contentText = financingBean.financingInterest.toString()
    }
}